package org.za.communication.core.codec.encoder;

import java.util.ArrayList;
import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.za.communication.core.handler.SessionIdleHandler;
import org.za.communication.core.util.DESPlus;
import org.za.communication.message.BaseMessage;

public class DataCombineEncoder extends ProtocolEncoderAdapter {

	private final static Logger log = LoggerFactory
			.getLogger(SessionIdleHandler.class);

	private byte[] head;
	private List<Integer> encryptIdList = new ArrayList<Integer>();

	public List<Integer> getEncryptIdList() {
		return encryptIdList;
	}

	public void setEncryptIdList(List<Integer> encryptIdList) {
		this.encryptIdList = encryptIdList;
	}

	public byte[] getHead() {
		return head;
	}

	public void setHead(byte[] head) {
		this.head = head;
	}

	@Override
	public void encode(IoSession session, Object data, ProtocolEncoderOutput out)
			throws Exception {

		if (data instanceof BaseMessage) {

			IoBuffer in = ((BaseMessage) data).getData();
			in.mark();
			int msgId = in.getUnsignedShort();
			in.reset();
			if (encryptIdList.contains(msgId)) {
				in.getUnsignedShort();
				byte[] key = new byte[4];
				in.get(key);
				int length = in.limit() - in.position();
				byte[] d = new byte[length];
				in.get(d);
				DESPlus des = new DESPlus(new String(key));
				d = des.encrypt(d);
				length = d.length + key.length + 2;
				IoBuffer outbuff = IoBuffer.allocate(length + head.length + 4);
				outbuff.put(head);
				outbuff.putInt(length);
				outbuff.putUnsignedShort(msgId);
				outbuff.put(key);
				outbuff.put(d);
				outbuff.flip();
				out.write(outbuff);
			} else {
				int length = in.limit();
				IoBuffer outbuff = IoBuffer.allocate(length + head.length + 4);
				outbuff.put(head);
				outbuff.putInt(length);
				outbuff.put(in);
				outbuff.flip();
				out.write(outbuff);
			}

		}

	}
}
